import React, { useState } from "react";
import style from "./style.module.scss";
import { MyNavBar } from "../../../components";
import { useNavigate } from "react-router-dom";
import boy from "../../../assets/images/image/hdpi/boy.png";
import girl from "../../../assets/images/image/hdpi/girl.png";
import selected from "../../../assets/images/image/hdpi/selected.png";
import { useAppDispatch, useAppSelector } from "../../../store/hooks";
import { updateUserSex } from "../../../api/my";
import { Toast } from "react-vant";
import { getUserInfo } from "../../../store/user/userSlice";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const sex = useAppSelector((state) => state.user.userInfo.sex);
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);

  const [sexInd, setSexInd] = useState(sex);

  const onUpdate = async () => {
    const resp = await updateUserSex(sexInd, userId, sessionId);
    const { message, status } = resp;

    if (status === "0000") {
      dispatch(getUserInfo({ userId: userId.toString(), sessionId }));
      Toast.success(message);
      navigate("/set/person/infomation");
    }
  };

  return (
    <div className={style.chooseGender}>
      <MyNavBar
        title="选择性别"
        rightText={
          <button className={style.btn} onClick={() => onUpdate()}>
            完成
          </button>
        }
        style={{ backgroundColor: "#fff" }}
        onClickLeft={() => navigate("/set/person/infomation")}
      ></MyNavBar>
      <div className={style.chooseGender_box}>
        <div className={style.boy_box}>
          <div className={style.selectedSex_box} onClick={() => setSexInd(1)}>
            <img src={boy} alt="" className={style.selectedSex} />
            {sexInd === 1 && (
              <img src={selected} alt="" className={style.activeIcon} />
            )}
          </div>
          <div className={style.boy_text}>男</div>
        </div>
        <div className={style.girl_box}>
          <div className={style.selectedSex_box} onClick={() => setSexInd(2)}>
            <img src={girl} alt="" className={style.selectedSex} />
            {sexInd === 2 && (
              <img src={selected} alt="" className={style.activeIcon} />
            )}
          </div>
          <div className={style.girl_text}>女</div>
        </div>
      </div>
    </div>
  );
};

export default Index;
